//
//  PictureItemView.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/3/1.
//

import SwiftUI
import Kingfisher
import AVFoundation
import SDWebImageSwiftUI
//网络图片、本地图片、本地视频
struct PictureItemView: View {
    var item: MediaItem
    let itemWidth : CGFloat
    let itemHeight : CGFloat
    var cornerRadius : CGFloat = 15
    @State private var isImageLoading = true
    
    // 压缩后的图片
    @State private var compressedImage: UIImage?
    var body: some View {
        ZStack{
            switch item.type {
            case .networkImage(let thumbnail, _, let isVideo):
                //                KFImage(URL(string: convertCdn(thumbnail)))
                //                    .resizable()
                //                    .setProcessor(DownsamplingImageProcessor(size: CGSize(width: itemWidth * 5, height: itemHeight * 5))) //按设置大小压缩，*5是，清晰度较高，不卡顿
                //                    .fade(duration: 0.1)
                //                    .diskCacheExpiration(.days(7)) // 设置磁盘缓存过期时间
                //                    .placeholder{
                //                        Image(.appDefaultLogo)
                //                            .resizable()
                //                            .scaledToFill()
                //                            .padding(.horizontal,itemWidth / 4)
                //                            .padding(.vertical,itemHeight / 4)
                //                    }
                //                    .scaledToFill()
                //                    .overlay(
                //                        ZStack{
                //                            if isVideo {
                //                                Image(systemName: "play.circle.fill")
                //                                    .resizable()
                //                                    .foregroundColor(Color.white)
                //                                    .frame(width: 15, height: 15, alignment: .center)
                //                            }
                //                        }
                //                    )
                ZStack {
                    //图片
                    if isImageLoading {
                        Image(.appDefaultLogo)
                            .resizable()
                            .scaledToFill()
                            .padding(.horizontal, itemWidth / 4)
                            .padding(.vertical, itemHeight / 4)
                            .frame(width: itemWidth,height: itemHeight)
                    }
                    AnimatedImage(url: URL(string: thumbnail.formatCdn()))
                        .onSuccess { _,_,_  in
                            DispatchQueue.main.async {
                                withAnimation(.easeIn(duration: 0.2)) {
                                    self.isImageLoading = false // 图片加载成功后，隐藏占位图
                                }
                            }
                        }
                        .resizable()
                        .scaledToFill()
                        .overlay(
                            ZStack {
                                if isVideo {
                                    Image(systemName: "play.circle.fill")
                                        .resizable()
                                        .foregroundColor(Color.white)
                                        .frame(width: 15, height: 15, alignment: .center)
                                }
                            }
                        )
                }
            case .localImage(let uiImage):
                Image(uiImage: uiImage)
                    .resizable()
                    .scaledToFill()
                    .frame(width: itemWidth, height: itemHeight)
                    .clipped()
            case .localImagePath(let fileUrlPath):
                //                KFImage(URL(fileURLWithPath: fileUrlPath))
                //                    .resizable()
                //                    .setProcessor(DownsamplingImageProcessor(size: CGSize(width: itemWidth * 5, height: itemHeight * 5)))
                //                    .placeholder{
                //                        Image(.appDefaultLogo)
                //                            .resizable()
                //                            .scaledToFill()
                //                            .padding(.horizontal,itemWidth / 4)
                //                            .padding(.vertical,itemHeight / 4)
                //                    }
                //                    .fade(duration: 0.1)
                //                    .diskCacheExpiration(.days(7)) // 设置磁盘缓存过期时间
                //                    .scaledToFill()
                //                    .frame(width: itemWidth, height: itemHeight)
                ZStack {
                    if isImageLoading {
                        Image(.appDefaultLogo)
                            .resizable()
                            .scaledToFill()
                            .padding(.horizontal, itemWidth / 4)
                            .padding(.vertical, itemHeight / 4)
                            .frame(width: itemWidth,height: itemHeight)
                    }
                    //图片
                    AnimatedImage(url: URL(fileURLWithPath: fileUrlPath))
                        .onSuccess { _,_,_  in
                            DispatchQueue.main.async {
                                withAnimation(.easeIn(duration: 0.2)) {
                                    self.isImageLoading = false // 图片加载成功后，隐藏占位图
                                }
                            }
                        }
                        .resizable()
                        .scaledToFill()
                }
            case .localVideo(let url):
                //本地视频，
                if let uiImage = generateThumbnail(videoURL: url) {
                    Image(uiImage: uiImage)
                        .resizable()
                        .scaledToFill()
                        .overlay(
                            ZStack{
                                Image(systemName: "play.circle.fill")
                                    .resizable()
                                    .foregroundColor(Color.white)
                                    .frame(width: 15, height: 15, alignment: .center)
                            }
                        )
                } else {
                    Image(.appDefaultLogo)
                        .resizable()
                        .scaledToFill()
                        .padding(10)
                }
                
            }
        }
        .frame(width: itemWidth,height: itemHeight)
        .background(.bg)
        .clipShape(RoundedRectangle(cornerRadius: cornerRadius))
        .overlay(
            ZStack{
                //圆角边框，比border效果好
                RoundedRectangle(cornerRadius: cornerRadius)
                    .stroke(Color.disabled, lineWidth: 1)
                
            }
        )
    }
    
    private func generateThumbnail(videoURL:URL) -> UIImage? {
        let asset = AVAsset(url: videoURL)
        let imageGenerator = AVAssetImageGenerator(asset: asset)
        imageGenerator.appliesPreferredTrackTransform = true
        
        let time = CMTime(seconds: 0, preferredTimescale: 60)
        do {
            let cgImage = try imageGenerator.copyCGImage(at: time, actualTime: nil)
            return UIImage(cgImage: cgImage)
        } catch {
            return nil
        }
    }
}

#Preview {
    PictureItemView(item: MediaItem(type: .networkImage("","", false)), itemWidth: 50, itemHeight: 50 )
}
